<template>
  <view class="game-room">
    <!-- 顶部导航 -->
    <view class="room-header">
      <view class="header-left" @click="leaveRoom">
        <text class="back-icon">←</text>
        <text class="back-text">返回</text>
      </view>
      <view class="header-center">
        <text class="room-no">房间号: {{ roomInfo.roomNo }}</text>
      </view>
      <view class="header-right">
        <!-- 微信小程序使用 button 的 open-type="share" 直接触发分享 -->
        <!-- #ifdef MP-WEIXIN -->
        <button class="share-button" open-type="share">
          <text class="share-text">邀请</text>
        </button>
        <!-- #endif -->
        <!-- H5 和 APP 端点击复制房间信息 -->
        <!-- #ifndef MP-WEIXIN -->
        <view @click="shareRoom">
          <text class="share-text">邀请</text>
        </view>
        <!-- #endif -->
      </view>
    </view>

    <!-- 房间信息 -->
    <view class="room-info-bar">
      <view class="info-item">
        <text class="info-label">房主</text>
        <text class="info-value">{{ roomInfo.ownerName }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">人数</text>
        <text class="info-value">{{ playerList.length }}/4</text>
      </view>
    </view>

    <!-- 玩家座位 -->
    <view class="player-seats">
      <!-- 上方玩家 -->
      <view class="seat-top">
        <view class="player-seat" :class="{ 'has-player': playerList[2] }">
          <view v-if="playerList[2]" class="player-info">
            <image class="player-avatar" :src="playerList[2].avatar || '/static/images/profile.jpg'" mode="aspectFill"></image>
            <text class="player-name">{{ playerList[2].nickName }}</text>
            <view v-if="playerList[2].isReady" class="ready-badge">准备</view>
          </view>
          <view v-else class="empty-seat">
            <text class="empty-text">等待加入</text>
          </view>
        </view>
      </view>

      <!-- 中间区域 -->
      <view class="seat-middle">
        <!-- 左边玩家 -->
        <view class="player-seat" :class="{ 'has-player': playerList[1] }">
          <view v-if="playerList[1]" class="player-info">
            <image class="player-avatar" :src="playerList[1].avatar || '/static/images/profile.jpg'" mode="aspectFill"></image>
            <text class="player-name">{{ playerList[1].nickName }}</text>
            <view v-if="playerList[1].isReady" class="ready-badge">准备</view>
          </view>
          <view v-else class="empty-seat">
            <text class="empty-text">等待加入</text>
          </view>
        </view>

        <!-- 中间桌面 -->
        <view class="table-center">
          <image class="table-bg" src="/static/images/table-bg.png" mode="aspectFit"></image>
          <view class="center-text">抓黑枪</view>
        </view>

        <!-- 右边玩家 -->
        <view class="player-seat" :class="{ 'has-player': playerList[3] }">
          <view v-if="playerList[3]" class="player-info">
            <image class="player-avatar" :src="playerList[3].avatar || '/static/images/profile.jpg'" mode="aspectFill"></image>
            <text class="player-name">{{ playerList[3].nickName }}</text>
            <view v-if="playerList[3].isReady" class="ready-badge">准备</view>
          </view>
          <view v-else class="empty-seat">
            <text class="empty-text">等待加入</text>
          </view>
        </view>
      </view>

      <!-- 下方玩家（自己） -->
      <view class="seat-bottom">
        <view class="player-seat has-player">
          <view v-if="playerList[0]" class="player-info">
            <image class="player-avatar" :src="playerList[0].avatar || '/static/images/profile.jpg'" mode="aspectFill"></image>
            <text class="player-name">{{ playerList[0].nickName }}（我）</text>
            <view v-if="playerList[0].isReady" class="ready-badge">准备</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作区 -->
    <view class="room-actions">
      <view v-if="isOwner && canStart" class="action-buttons">
        <button class="btn-start" @click="startGame">开始游戏</button>
      </view>
      <view v-else class="action-buttons">
        <button 
          class="btn-ready" 
          :class="{ 'is-ready': myReadyStatus }"
          @click="toggleReady"
        >
          {{ myReadyStatus ? '取消准备' : '准备' }}
        </button>
      </view>
      
      <view class="tips-text">
        <text v-if="!canStart">等待其他玩家加入（{{ playerList.length }}/4）</text>
        <text v-else-if="!allReady && !isOwner">请等待其他玩家准备</text>
        <text v-else-if="isOwner">所有玩家已准备，可以开始游戏</text>
      </view>
    </view>

    <!-- 右侧好友列表侧边栏 -->
    <!-- #ifdef MP-WEIXIN -->
    <view class="friend-sidebar" :class="{ 'show': showFriendList }">
      <!-- 侧边栏头部 -->
      <view class="sidebar-header">
        <text class="sidebar-title">邀请好友</text>
        <view class="close-btn" @click="toggleFriendList">
          <text class="close-icon">×</text>
        </view>
      </view>

      <!-- 好友列表 - 使用开放数据域 -->
      <view class="friend-list-container">
        <!-- 使用开放数据域组件显示好友 -->
        <open-data-friends ref="openDataFriends" class="friend-canvas"></open-data-friends>
        
        <!-- 提示信息 -->
        <view class="friend-list-tip">
          <text class="tip-text">显示玩过此游戏的微信好友</text>
          <button class="invite-all-btn" open-type="share">
            邀请更多好友
          </button>
        </view>
      </view>
    </view>

    <!-- 悬浮按钮 - 打开好友列表 -->
    <view class="float-friend-btn" @click="toggleFriendList" v-if="!showFriendList">
      <text class="float-icon">👥</text>
      <text class="float-text">好友</text>
    </view>

    <!-- 遮罩层 -->
    <view class="sidebar-mask" v-if="showFriendList" @click="toggleFriendList"></view>
    <!-- #endif -->
  </view>
</template>

<script>
import { getRoomDetail, leaveRoom, toggleReady, startGame } from '@/api/game'
import OpenDataFriends from '@/components/open-data-friends/open-data-friends.vue'

export default {
  components: {
    OpenDataFriends
  },
  data() {
    return {
      roomId: '',
      roomInfo: {
        roomNo: '',
        ownerName: '',
        ownerId: ''
      },
      playerList: [],
      myUserId: '',
      pollingTimer: null,
      showFriendList: false,
      friendList: [] // 微信好友列表（实际需要通过微信API获取）
    }
  },
  
  computed: {
    // 是否是房主
    isOwner() {
      return this.myUserId === this.roomInfo.ownerId
    },
    
    // 是否可以开始（4人到齐）
    canStart() {
      return this.playerList.length === 4
    },
    
    // 所有人是否准备
    allReady() {
      return this.playerList.every(p => p.isReady || p.userId === this.roomInfo.ownerId)
    },
    
    // 我的准备状态
    myReadyStatus() {
      const myInfo = this.playerList.find(p => p.userId === this.myUserId)
      return myInfo ? myInfo.isReady : false
    }
  },
  
  onLoad(options) {
    console.log('房间页面参数:', options)
    this.roomId = options.roomId
    this.myUserId = uni.getStorageSync('userId') || uni.getStorageSync('userInfo')?.userId
    
    // 检查 roomId 是否有效
    if (!this.roomId || this.roomId === 'undefined') {
      uni.showToast({
        title: '房间ID无效',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    
    this.loadRoomDetail()
    this.startPolling()
    this.loadFriendList()
  },
  
  onUnload() {
    this.stopPolling()
  },
  
  methods: {
    // 切换好友列表显示
    toggleFriendList() {
      this.showFriendList = !this.showFriendList
    },
    
    // 加载好友列表（从后端获取已注册游戏的好友）
    async loadFriendList() {
      try {
        // 方式1: 获取最近一起玩过的玩家
        const recentRes = await this.$request({
          url: '/api/game/friends/recent',
          method: 'GET'
        })
        
        if (recentRes.code === 200) {
          this.friendList = recentRes.data.map(friend => ({
            id: friend.userId,
            name: friend.userName,
            avatar: friend.avatar || '/static/images/profile.jpg',
            status: friend.isOnline ? '在线' : '离线',
            isOnline: friend.isOnline
          }))
        }
        
        // 如果没有最近玩家，可以尝试获取其他来源的好友
        if (this.friendList.length === 0) {
          // 方式2: 通过微信群获取（需要用户授权）
          // 这需要用户主动分享到微信群，然后通过群ID获取群成员
          console.log('暂无最近一起玩的好友')
        }
      } catch (error) {
        console.error('加载好友列表失败:', error)
        // 如果后端接口还未实现，显示友好提示
        this.friendList = []
      }
    },
    
    // 加载房间详情
    async loadRoomDetail() {
      // 再次检查 roomId
      if (!this.roomId || this.roomId === 'undefined') {
        console.error('roomId 无效，停止加载')
        this.stopPolling()
        return
      }
      
      try {
        const res = await getRoomDetail(this.roomId)
        
        if (res.code === 200) {
          // 后端返回的数据直接在 res.data 中，不是 res.data.room
          const owner = res.data.players.find(p => p.isOwner)
          
          this.roomInfo = {
            roomNo: res.data.roomId,
            roomId: res.data.roomId,
            roomName: res.data.roomName,
            maxPlayers: res.data.maxPlayers,
            status: res.data.status,
            ownerId: owner?.userId || '',
            ownerName: owner?.userName || ''
          }
          
          // 映射玩家数据，nickName 字段对应 userName
          this.playerList = (res.data.players || []).map(player => ({
            ...player,
            nickName: player.userName,
            avatar: player.avatar || '/static/images/profile.jpg'
          }))
          
          // 如果游戏已开始，跳转到游戏页面
          // status: 'waiting' 或 'playing'
          if (res.data.status === 'playing') {
            uni.redirectTo({
              url: `/pages/game/play/index?roomId=${this.roomId}`
            })
          }
        } else if (res.code === 500 && res.msg === '房间不存在') {
          // 房间不存在，停止轮询并返回
          this.stopPolling()
          uni.showToast({
            title: '房间已解散',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (err) {
        console.error('加载房间详情失败', err)
        // 如果是房间不存在的错误，停止轮询
        if (err.message && err.message.includes('房间不存在')) {
          this.stopPolling()
        }
      }
    },
    
    // 开始轮询
    startPolling() {
      this.pollingTimer = setInterval(() => {
        this.loadRoomDetail()
      }, 2000)
    },
    
    // 停止轮询
    stopPolling() {
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer)
        this.pollingTimer = null
      }
    },
    
    // 离开房间
    async leaveRoom() {
      uni.showModal({
        title: '提示',
        content: '确定要离开房间吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await leaveRoom(this.roomId)
              uni.navigateBack()
            } catch (err) {
              console.error('离开房间失败', err)
              
              // 显示具体的错误信息
              let errorMsg = '离开失败'
              if (err.message) {
                errorMsg = err.message
              } else if (typeof err === 'string') {
                errorMsg = err
              }
              
              uni.showToast({
                title: errorMsg,
                icon: 'none',
                duration: 2000
              })
            }
          }
        }
      })
    },
    
    // 分享房间（仅用于 H5 和 APP 端）
    shareRoom() {
      // #ifndef MP-WEIXIN
      uni.setClipboardData({
        data: `房间号：${this.roomInfo.roomNo}\n密码：${this.roomInfo.password || '无'}\n快来一起玩河北麻将！`,
        success: () => {
          uni.showToast({
            title: '房间信息已复制',
            icon: 'success'
          })
        }
      })
      // #endif
    },
    
    // 切换准备状态
    async toggleReady() {
      try {
        const res = await toggleReady(this.roomId)
        
        if (res.code === 200) {
          this.loadRoomDetail()
          uni.showToast({
            title: this.myReadyStatus ? '已取消准备' : '已准备',
            icon: 'success'
          })
        }
      } catch (err) {
        console.error('准备失败', err)
        
        // 显示具体的错误信息
        let errorMsg = '操作失败'
        if (err.message) {
          errorMsg = err.message
        } else if (typeof err === 'string') {
          errorMsg = err
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 开始游戏
    async startGame() {
      if (!this.canStart) {
        uni.showToast({
          title: '人数不足，需要4人',
          icon: 'none'
        })
        return
      }
      
      if (!this.allReady) {
        uni.showToast({
          title: '请等待所有玩家准备',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({ title: '正在开始...' })
        
        const res = await startGame(this.roomId)
        
        uni.hideLoading()
        
        if (res.code === 200) {
          uni.showToast({
            title: '游戏开始！',
            icon: 'success'
          })
          
          // 跳转到游戏页面
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/game/play/index?roomId=${this.roomId}`
            })
          }, 500)
        }
      } catch (err) {
        uni.hideLoading()
        console.error('开始游戏失败', err)
        
        // 显示具体的错误信息
        let errorMsg = '开始失败'
        if (err.message) {
          errorMsg = err.message
        } else if (typeof err === 'string') {
          errorMsg = err
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
      }
    }
  },
  
  // 微信小程序分享配置
  onShareAppMessage(res) {
    // res.from 可以判断来源：button（按钮触发）或 menu（右上角菜单触发）
    console.log('分享来源：', res.from)
    
    return {
      title: `${this.roomInfo.ownerName}邀请你一起玩河北麻将！`,
      path: `/pages/game/room/index?roomId=${this.roomId}`,
      imageUrl: '/static/images/share-cover.jpg', // 可以自定义分享图片
      success: (shareRes) => {
        console.log('分享成功', shareRes)
        uni.showToast({
          title: '邀请已发送',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.log('分享失败', err)
      }
    }
  },
  
  onShareTimeline() {
    return {
      title: `${this.roomInfo.ownerName}邀请你一起玩河北麻将！房间号：${this.roomInfo.roomNo}`,
      query: `roomId=${this.roomId}`,
      imageUrl: '/static/images/share-cover.jpg'
    }
  }
}
</script>

<style lang="scss" scoped>
.game-room {
  min-height: 100vh;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  display: flex;
  flex-direction: column;
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: rgba(255, 255, 255, 0.1);
  
  .header-left {
    display: flex;
    align-items: center;
    color: #fff;
    
    .back-icon {
      font-size: 36rpx;
      margin-right: 10rpx;
    }
    
    .back-text {
      font-size: 28rpx;
    }
  }
  
  .header-center {
    .room-no {
      font-size: 28rpx;
      color: #fff;
      font-weight: bold;
    }
  }
  
  .header-right {
    .share-button {
      background: transparent;
      border: none;
      padding: 0;
      margin: 0;
      line-height: normal;
      
      &::after {
        border: none;
      }
    }
    
    .share-text {
      font-size: 28rpx;
      color: #fff;
      padding: 10rpx 20rpx;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 20rpx;
      display: inline-block;
    }
  }
}

.room-info-bar {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 30rpx;
  background: rgba(255, 255, 255, 0.1);
  
  .info-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .info-label {
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.7);
      margin-bottom: 5rpx;
    }
    
    .info-value {
      font-size: 28rpx;
      color: #fff;
      font-weight: bold;
    }
  }
}

.player-seats {
  flex: 1;
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.seat-top, .seat-bottom {
  display: flex;
  justify-content: center;
}

.seat-middle {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.player-seat {
  width: 180rpx;
  height: 220rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx dashed rgba(255, 255, 255, 0.3);
  
  &.has-player {
    background: rgba(255, 255, 255, 0.15);
    border: 2rpx solid rgba(255, 255, 255, 0.5);
  }
  
  .player-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    
    .player-avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      margin-bottom: 15rpx;
      border: 3rpx solid #fff;
    }
    
    .player-name {
      font-size: 24rpx;
      color: #fff;
      text-align: center;
      max-width: 160rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .ready-badge {
      position: absolute;
      top: 0;
      right: -10rpx;
      background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
      color: #fff;
      font-size: 20rpx;
      padding: 5rpx 15rpx;
      border-radius: 20rpx;
      font-weight: bold;
    }
  }
  
  .empty-seat {
    .empty-text {
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.5);
    }
  }
}

.table-center {
  width: 300rpx;
  height: 300rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  border: 3rpx solid rgba(255, 255, 255, 0.3);
  
  .table-bg {
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0.3;
  }
  
  .center-text {
    font-size: 48rpx;
    color: #fff;
    font-weight: bold;
    z-index: 1;
  }
}

.room-actions {
  padding: 30rpx;
  background: rgba(255, 255, 255, 0.1);
  
  .action-buttons {
    margin-bottom: 20rpx;
    
    button {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      font-size: 32rpx;
      font-weight: bold;
      border: none;
    }
    
    .btn-start {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      color: #fff;
    }
    
    .btn-ready {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      color: #fff;
      
      &.is-ready {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
      }
    }
  }
  
  .tips-text {
    text-align: center;
    
    text {
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.7);
    }
  }
}

// 右侧好友列表侧边栏
.friend-sidebar {
  position: fixed;
  top: 0;
  right: -600rpx;
  width: 600rpx;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: -5rpx 0 30rpx rgba(0, 0, 0, 0.3);
  z-index: 1000;
  transition: right 0.3s ease;
  display: flex;
  flex-direction: column;
  
  &.show {
    right: 0;
  }
  
  .sidebar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    background: rgba(0, 0, 0, 0.1);
    border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
    
    .sidebar-title {
      font-size: 32rpx;
      color: #fff;
      font-weight: bold;
    }
    
    .close-btn {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .close-icon {
        font-size: 50rpx;
        color: #fff;
        line-height: 1;
      }
    }
  }
  
  .friend-list-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .friend-canvas {
      flex: 1;
      width: 100%;
      overflow: hidden;
    }
    
    .friend-list-tip {
      padding: 20rpx;
      border-top: 1rpx solid rgba(255, 255, 255, 0.1);
      text-align: center;
      
      .tip-text {
        display: block;
        font-size: 22rpx;
        color: rgba(255, 255, 255, 0.6);
        margin-bottom: 15rpx;
      }
      
      .invite-all-btn {
        width: 100%;
        padding: 20rpx;
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        color: #fff;
        font-size: 26rpx;
        border-radius: 50rpx;
        border: none;
        
        &::after {
          border: none;
        }
      }
    }
  }
}

// 悬浮按钮
.float-friend-btn {
  position: fixed;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 5rpx 20rpx rgba(0, 0, 0, 0.3);
  z-index: 999;
  transition: all 0.3s;
  
  &:active {
    transform: translateY(-50%) scale(0.95);
  }
  
  .float-icon {
    font-size: 40rpx;
    margin-bottom: 5rpx;
  }
  
  .float-text {
    font-size: 20rpx;
    color: #fff;
  }
}

// 遮罩层
.sidebar-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
}
</style>
